from typing import List
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from db.session import get_db
from schemas.issue import Issue, IssueCreate, IssueUpdate, IssueDeleteRequest
from crud.issue import (
    get_issue,
    get_issues_by_plan,
    create_issue as crud_create_issue,
    update_issue as crud_update_issue,
    delete_issues as crud_delete_issues,
)
from log import log_info, log_error

router = APIRouter(prefix="/issues", tags=["issues"])

@router.get("/{issue_id}", response_model=Issue)
async def read_issue(issue_id: UUID, db: AsyncSession = Depends(get_db)):
    """Get a specific issue by ID."""
    try:
        db_issue = await get_issue(db, issue_id=issue_id)
        if db_issue is None:
            raise HTTPException(status_code=404, detail="Issue not found")
        return db_issue
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/plan/{plan_id}", response_model=List[Issue])
async def read_issues_by_plan(plan_id: UUID, skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db)):
    """Get all issues for a specific assessment plan."""
    try:
        return await get_issues_by_plan(db, plan_id=plan_id, skip=skip, limit=limit)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/", response_model=Issue, status_code=status.HTTP_201_CREATED)
async def create_new_issue(issue: IssueCreate, db: AsyncSession = Depends(get_db)):
    """Create a new issue."""
    try:
        return await crud_create_issue(db=db, issue=issue)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{issue_id}", response_model=Issue)
async def update_issue(
    issue_id: UUID, issue: IssueUpdate, db: AsyncSession = Depends(get_db)
):
    """Update an existing issue."""
    try:
        db_issue = await get_issue(db, issue_id=issue_id)
        if db_issue is None:
            raise HTTPException(status_code=404, detail="Issue not found")
        return await crud_update_issue(db=db, db_issue=db_issue, issue=issue)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/", response_model=int)
async def delete_issues(payload: IssueDeleteRequest, db: AsyncSession = Depends(get_db)):
    """Delete multiple issues."""
    try:
        if not payload.ids:
            raise HTTPException(status_code=400, detail="ID list cannot be empty")
        log_info(f"批量删除问题项: {len(payload.ids)} 个", module="crud.issue")
        deleted_count = await crud_delete_issues(db=db, issue_ids=payload.ids)
        log_info(f"成功删除 {deleted_count} 个问题项", module="crud.issue")
    except Exception as e:
        log_error(f"批量删除问题项失败: {str(e)}", module="crud.issue")
        raise HTTPException(status_code=500, detail=str(e))
    return deleted_count
